import axios from 'axios'

// 创建axios实例
const service = axios.create({
    baseURL: 'http://localhost:8081', // 配置API地址
    timeout: 5000 // 请求超时时间
})

// 请求拦截器
service.interceptors.request.use(
    config => {
        // 从localStorage获取token
        const token = localStorage.getItem('token')
        if (token) {
            config.headers['token'] = token
        }
        return config
    },
    error => {
        console.log(error)
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    response => {
        const res = response.data
        return res
    },
    error => {
        console.log('err' + error)
        return Promise.reject(error)
    }
)

// 登录接口（适配表单参数）
export const login = (username, password) => {
    const params = new URLSearchParams()
    params.append('username', username)
    params.append('password', password)
    return service.post('/findUser', params)
}

export default service